﻿angular.module("app").controller('DjinnCtrl', function($scope, $interval, djinnData) {
  var interval = 250.0;
  $scope.Djinn = djinnData.getDjinnList();
  $scope.UnlockedLevels = djinnData.getUnlockedlevels();
  $scope.testThing = [1, 3, 5, 7, 6, 4, 2];
  var tickMethod = function() {
    for (var i = 0; i < $scope.Djinn.length; i++) {
      var djinni = $scope.Djinn[i];
      djinni.pp += (djinni.tickMulti * djinni.tick) * (interval / 1000.0);
      djinni.display = Math.floor(djinni.pp);
      $scope.Flags(djinni);
    }
  };

  var countdownInterval;

  var startCountdown = function() {
    countdownInterval = $interval(tickMethod, interval, $scope.countdown);
  };

  $scope.Click = function(djinni) {
    djinni.pp += (djinni.clickMulti * djinni.click);
  };

  $scope.BuyThing = function(djinni, thing) {
    if (djinni.pp >= thing.cost) {
      djinni.pp -= thing.cost;
      thing.num += 1;
      thing.cost *= 1.2;
      thing.cost = Math.floor(thing.cost);
      djinni.tick += thing.buff;
    }
  };

  $scope.Flags = function (djinni) {
    var msg = "";
    for (var i = 0; i < djinni.Things.length; i++) {
      var thing = djinni.Things[i];
      if (djinni.pp >= thing.cost) {
        thing.flag = true;
        $scope.UnlockedLevels[i].flag = $scope.changeUnlock(i);
        msg+=(i+":"+$scope.UnlockedLevels[i].flag+" ");
      } else {
        thing.flag = false;
        $scope.UnlockedLevels[i].flag = $scope.changeUnlock(i);
        msg+=(i+":"+$scope.UnlockedLevels[i].flag+" ");
      }
    }
    console.log(msg);
  };

  $scope.changeUnlock = function (i) {
    var ret = false;
    for (var j = 0; j < $scope.Djinn.length; j++) {
      ret = $scope.Djinn[j].Things[i].flag || ret;
    }
    return ret;
  };

  startCountdown();
});